const { FailModel } = require("../utils/model_adapter");
const { privateKey, dePrivatecrypt } = require("../utils/rsa");

async function checkLogin(ctx, next) {
  const token = ctx.headers["x-token"];

  if (!token) {
    return (ctx.body = new FailModel("非法请求", { code: 401 }));
  }
  try {
    const info = dePrivatecrypt(token, privateKey);

    if (
      !info.txt ||
      !info.expired ||
      !info.kk ||
      !info.card_count ||
      !info.card_program_type
    ) {
      return (ctx.body = new FailModel("非法请求", { code: 401 }));
    }

    if (Math.round(Date.now() / 1000) - info.expired > 86400) {
      return (ctx.body = new FailModel("卡密过期或不可用", {
        data: "",
        code: 401,
      }));
    }
    return await next();
  } catch (error) {
    ctx.body = new FailModel("非法请求", { code: 401 });
  }
}

module.exports = checkLogin;
